package com.huawei.chengdu.meetingdemo.view.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.device.idea.meeting.ConfCtrl.model.ResultMsgInfo;
import com.device.idea.meeting.MeetingCallback;
import com.huawei.chengdu.meetingdemo.R;
import com.huawei.chengdu.meetingdemo.consts.DialogConst;
import com.huawei.chengdu.meetingdemo.model.ConfSiteInfo;
import com.huawei.chengdu.meetingdemo.model.GalleryBean;
import com.huawei.chengdu.meetingdemo.presenter.ConfSdkPresenter;
import com.huawei.chengdu.meetingdemo.util.LogUtil;
import com.huawei.chengdu.meetingdemo.util.ScreenUtil;
import com.huawei.chengdu.meetingdemo.presenter.MeetingManager;
import com.huawei.chengdu.meetingdemo.view.dialogs.CustomFloatWindow;
import com.huawei.chengdu.meetingdemo.view.dialogs.FloatWindowCustomBase;
import com.huawei.chengdu.meetingdemo.view.dialogs.ParticipantsDialog;

import java.util.concurrent.CopyOnWriteArrayList;

public class ParticipantsAdapter extends RecyclerView.Adapter<ParticipantsAdapter.ParticipantViewHolder> {
    private static final String TAG = "ParticipantsAdapter";

    private Context mContext;

    private ParticipantsDialog participantsDialog;

    private CopyOnWriteArrayList<GalleryBean> siteList = new CopyOnWriteArrayList<>();

    private CopyOnWriteArrayList<GalleryBean> inConfSiteList = new CopyOnWriteArrayList<>();

    private CopyOnWriteArrayList<GalleryBean> unConfSiteList = new CopyOnWriteArrayList<>();

    private LayoutInflater inflater;

    // 本地会场是否是主席，和VH里的区分
    private boolean isLocalChair;

    /**
     * 构造器
     *
     * @param mContext           上下文
     * @param participantsDialog 与会者dialog
     */
    public ParticipantsAdapter(Context mContext, ParticipantsDialog participantsDialog) {
        this.mContext = mContext;
        this.participantsDialog = participantsDialog;
        inflater = LayoutInflater.from(mContext);
    }

    /**
     * 装填数据
     *
     * @param sites 会场列表
     */
    public void setData(CopyOnWriteArrayList<GalleryBean> sites) {
        LogUtil.info(TAG + " setData() , size : " + sites.size());
        siteList.clear();
        inConfSiteList.clear();
        unConfSiteList.clear();

        for (GalleryBean bean : sites) {
            if (!(bean instanceof ConfSiteInfo)) {
                continue;
            }
            ConfSiteInfo site = (ConfSiteInfo) bean;
            if (!site.isJoinConf()) {
                unConfSiteList.add(bean);
                continue;
            }
            inConfSiteList.add(bean);
        }
        LogUtil.info(TAG + "setData() , inConfSiteList.size : " + inConfSiteList.size());
        LogUtil.info(TAG + "setData() , unConfSiteList.size : " + unConfSiteList.size());
        siteList.addAll(inConfSiteList);
        siteList.addAll(unConfSiteList);
        for (GalleryBean galleryBean : siteList) {
            if (galleryBean instanceof ConfSiteInfo) {
                ConfSiteInfo tempInfo = (ConfSiteInfo) galleryBean;
                LogUtil.info(TAG + tempInfo);
            }
        }
        isLocalChair = MeetingManager.getInstance().isMeChairman();
        participantsDialog.refreshSiteCount(siteList.size() - 1, inConfSiteList.size() - 1);
        this.notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ParticipantViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.participant_item_layout, parent, false);
        return new ParticipantViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ParticipantViewHolder holder, int position) {
        holder.initData(position);
    }

    @Override
    public int getItemCount() {
        return siteList.size();
    }

    /**
     * 与会者列表数据VH
     */
    class ParticipantViewHolder extends RecyclerView.ViewHolder {
        private ImageView ivSiteIcon;

        private TextView tvSiteName;

        private TextView tvChair;

        private TextView tvSharing;

        private TextView tvViewed;

        private TextView tvBroadcast;

        private RelativeLayout firstGap;

        private RelativeLayout secondGap;

        private RelativeLayout thirdGap;

        private ImageView ivMic;

        private ImageView ivOperation;

        private LinearLayout llInConfOpt;

        private LinearLayout llNotInConfOpt;

        private LinearLayout llInConfStatus;

        private LinearLayout llNotInConfStatus;

        private ImageView ivCall;

        private ImageView ivDeleteSite;

        private boolean isLocalSite;

        private boolean isMuted;

        private int position;

        // 当前会场是否是主席
        private boolean isCurSiteChair;

        private boolean isInConf;

        private boolean isVoiceSite;

        private boolean isMultiScr;

        private boolean isSharing;

        private boolean isViewed;

        private boolean isBroadcasting;

        private ConfSiteInfo curSite;

        private MoreOperationListener moreOperationListener;

        /**
         * 构造器
         *
         * @param itemView view
         */
        public ParticipantViewHolder(@NonNull View itemView) {
            super(itemView);
            initView(itemView);
        }

        private void initView(View itemView) {
            LogUtil.info(TAG + "initView()");
            ivSiteIcon = itemView.findViewById(R.id.iv_site_icon);
            tvSiteName = itemView.findViewById(R.id.tv_site_name);
            tvChair = itemView.findViewById(R.id.tv_chair);
            tvSharing = itemView.findViewById(R.id.tv_sharing);
            tvViewed = itemView.findViewById(R.id.tv_viewed);
            tvBroadcast = itemView.findViewById(R.id.tv_broadcast);
            ivMic = itemView.findViewById(R.id.iv_mic);
            ivOperation = itemView.findViewById(R.id.iv_site_operation);

            firstGap = itemView.findViewById(R.id.first_gap);
            secondGap = itemView.findViewById(R.id.second_gap);
            thirdGap = itemView.findViewById(R.id.third_gap);

            llInConfOpt = itemView.findViewById(R.id.ll_inconf_operation);
            llNotInConfOpt = itemView.findViewById(R.id.ll_not_inconf_operation);
            llInConfStatus = itemView.findViewById(R.id.ll_inconf_status);
            llNotInConfStatus = itemView.findViewById(R.id.ll_not_inconf_status);

            ivCall = itemView.findViewById(R.id.iv_call);
            ivDeleteSite = itemView.findViewById(R.id.iv_delete_site);
        }

        private void initEvent() {
            // 麦克风
            ivMic.setOnClickListener(view -> handleMute());

            // 呼叫
            ivCall.setOnClickListener(view -> handleCall());

            // 删除
            ivDeleteSite.setOnClickListener(view -> handleDelete());

            // 更多
            moreOperationListener = new MoreOperationListener(curSite);
            ivOperation.setOnClickListener(moreOperationListener);
        }

        private void handleDelete() {
            LogUtil.info(TAG + "handleDelete() , pos : " + position);
            if (curSite == null) {
                return;
            }
            showDelDialog();
        }

        private void showDelDialog() {
            CustomFloatWindow.hideFloatWindow(DialogConst.DELETE_SITE_DLG);
            CustomFloatWindow deleteSiteConfirmDlg = new CustomFloatWindow(mContext, DialogConst.DELETE_SITE_DLG,
                    mContext.getString(R.string.notice_delete_site), mContext.getString(R.string.confirm),
                    mContext.getString(R.string.cancel));
            deleteSiteConfirmDlg.setBthHighLight(FloatWindowCustomBase.HIGH_LIGHT_OK);
            deleteSiteConfirmDlg.setCallBack(new FloatWindowCustomBase.OnBtnClickCallBack() {
                @Override
                public void isOkBtnClick() {
                    deleteSite();
                    CustomFloatWindow.hideFloatWindow(DialogConst.DELETE_SITE_DLG);
                }

                @Override
                public void isCancelBtnClick() {
                    CustomFloatWindow.hideFloatWindow(DialogConst.DELETE_SITE_DLG);
                }
            });
            deleteSiteConfirmDlg.showFloatWindow(60);
        }

        private void deleteSite() {
            ConfSdkPresenter.deleteAttendee(curSite.getParticipantInfo().getSiteName(), curSite.getParticipantInfo().getUserId(),
                    new MeetingCallback<ResultMsgInfo>() {
                        @Override
                        public void onSuccess(ResultMsgInfo succMsg) {
                            LogUtil.info(TAG + "deleteSite() success ,  succMsg:" + succMsg);
                        }

                        @Override
                        public void onFailed(int errCode, String errMsg) {
                            LogUtil.info(TAG + "deleteSite() failed ,  errCode:" + errCode + ", errMsg:" + errMsg);
                        }
                    });
        }

        private void handleCall() {
            LogUtil.info(TAG + "handleCall() , pos : " + position);
            if (curSite == null) {
                return;
            }
            if (!isLocalChair) {
                participantsDialog.needChairNotify();
                return;
            }
            MeetingManager.getInstance()
                    .callAttendee(curSite.getParticipantInfo().getSiteName(), curSite.getParticipantInfo().getUserId(),
                            new MeetingCallback() {
                                @Override
                                public void onSuccess(Object succMsg) {
                                    LogUtil.info(TAG + "handleCall()  success , succMsg:" + succMsg);
                                }

                                @Override
                                public void onFailed(int errCode, String errMsg) {
                                    LogUtil.info(TAG + "handleCall()  failed ,  errCode:" + errCode + ", errMsg:" + errMsg);
                                }
                            });
            participantsDialog.showCallSiteNotify();
        }

        private void handleMute() {
            LogUtil.info(TAG + "handleMute() . pos : " + position);
            if (ScreenUtil.isClickFast() || !isInConf) {
                return;
            }
            if (isLocalSite || isLocalChair) {
                MeetingManager.getInstance()
                        .quietAttendee(curSite.getParticipantInfo().getUserId(), !isMuted,
                                new MeetingCallback() {
                                    @Override
                                    public void onSuccess(Object succMsg) {
                                        LogUtil.info("handleMute() success , pos : " + position);
                                        isMuted = !isMuted;
                                        ivMic.post(() -> ivMic.setBackground(mContext.getDrawable(isMuted
                                                ? R.drawable.participant_mic_close_background
                                                : R.drawable.participant_mic_open_background)));
                                    }

                                    @Override
                                    public void onFailed(int errCode, String errMsg) {
                                        LogUtil.info("handleMute() failed , pos : " + position + " errCode :" + errCode + ", errMsg:"
                                                + errMsg);
                                    }
                                });
                return;
            }

            // 非主席点了其他人的mic , 弹需申请主席吐司
            participantsDialog.needChairNotify();
        }

        /**
         * 初始化数据
         *
         * @param position pos
         */
        public void initData(int position) {
            LogUtil.info(TAG + "initData() , pos : " + position);
            this.position = position;
            GalleryBean galleryBean = siteList.get(position);
            if (!(galleryBean instanceof ConfSiteInfo)) {
                return;
            }
            curSite = (ConfSiteInfo) galleryBean;
            isLocalSite = (curSite.getParticipantInfo().getUserId() == MeetingManager.getInstance().getLocalUserId());
            isCurSiteChair = curSite.getParticipantInfo().isChair();
            isVoiceSite = curSite.getParticipantInfo().isPSTN();
            isInConf = curSite.isJoinConf();
            isSharing = curSite.getParticipantInfo().isSharing();
            isViewed = curSite.getParticipantInfo().isViewed();
            isBroadcasting = curSite.getParticipantInfo().isBroadcasting();

            siteIconSet(curSite);
            siteNameSet(curSite);

            if (isInConf) {
                inConfSet(curSite);
            } else {
                notInConfSet();
            }

            ivMic.setTag(position);
            ivOperation.setTag(position);

            if (moreOperationListener != null) {
                moreOperationListener.dismissPopWindow();
            }
            initEvent();
        }

        private void siteIconSet(ConfSiteInfo site) {
            LogUtil.info(TAG + "siteIconSet()");
            if (isLocalSite) { // 本地会场
                ivSiteIcon.setImageResource(R.drawable.participant_local);
                return;
            }

            if (site.tpMain != 0) {
                ivSiteIcon.setImageResource(R.drawable.particiment_tp3_screen);
                return;
            }

            ivSiteIcon.setImageResource(R.drawable.participant_remote);
        }

        private void siteNameSet(ConfSiteInfo site) {
            LogUtil.info(TAG + "siteNameSet()");
            String siteName = site.getParticipantInfo().getSiteName();
            String multiScrStr = mContext.getString(R.string.mutipic_site_txt);
            isMultiScr = multiScrStr.equals(siteName);
            if (isMultiScr) {
                ivMic.setVisibility(View.INVISIBLE);
                ivSiteIcon.setImageResource(R.drawable.particiment_tp3_screen);
            }

            if (isLocalSite) {
                String me = mContext.getString(R.string.me);
                siteName = siteName + " " + me;
                ivMic.setVisibility(View.VISIBLE);
                ivMic.setBackground(mContext.getDrawable(isMuted
                        ? R.drawable.participant_mic_close_background
                        : R.drawable.participant_mic_open_background));
            }
            tvSiteName.setText(siteName);
        }

        private void inConfSet(ConfSiteInfo site) {
            LogUtil.info(TAG + "inConfSet()");
            llInConfOpt.setVisibility(View.VISIBLE);
            llNotInConfOpt.setVisibility(View.GONE);
            llInConfStatus.setVisibility(View.VISIBLE);
            llNotInConfStatus.setVisibility(View.GONE);

            initInConfStatusLayout();

            // 麦克风状态
            isMuted = site.getParticipantInfo().isMute();
            ivMic.setBackground(mContext.getDrawable(
                    isMuted ? R.drawable.participant_mic_close_background : R.drawable.participant_mic_open_background));
            if (isMultiScr) { // 多画面 不显示mic
                ivMic.setVisibility(View.INVISIBLE);
            } else if (isLocalChair) { // 主席显示所有mic
                ivMic.setVisibility(View.VISIBLE);
            } else { // 非主席只显示自己的mic
                ivMic.setVisibility(isLocalSite ? View.VISIBLE : View.INVISIBLE);
            }
        }

        /**
         * 初始化 主席、共享、观看、广播状态界面
         */
        private void initInConfStatusLayout() {
            // 1. 判断是否是语音会场
            if (isVoiceSite) { // 语音会场，只需关注主席状态
                audioSiteSet();
            } else { // 视频会场，关注共享、观看、广播状态
                videoSiteSet();
            }
        }

        private void audioSiteSet() {
            // 借用一下“共享中”的textView
            tvSharing.setText(R.string.voice_site);
            tvSharing.setVisibility(View.VISIBLE);

            // 主席分隔线
            firstGap.setVisibility(isCurSiteChair ? View.VISIBLE : View.GONE);
            tvChair.setVisibility(isCurSiteChair ? View.VISIBLE : View.GONE);
            // 不关注 观看、广播 ， 隐藏
            secondGap.setVisibility(View.GONE);
            tvViewed.setVisibility(View.GONE);
            thirdGap.setVisibility(View.GONE);
            tvBroadcast.setVisibility(View.GONE);
        }

        private void videoSiteSet() {
            // 先把文字置回"共享中"
            tvSharing.setText(R.string.participant_sharing);
            // 2. 广播中
            tvBroadcast.setVisibility(isBroadcasting ? View.VISIBLE : View.GONE);

            // 3.1 观看中
            tvViewed.setVisibility(isViewed ? View.VISIBLE : View.GONE);
            // 3.2 第三个分隔线
            if (isViewed && isBroadcasting) {
                thirdGap.setVisibility(View.VISIBLE);
            } else {
                thirdGap.setVisibility(View.GONE);
            }
            // 4.1 共享中
            tvSharing.setVisibility(isSharing ? View.VISIBLE : View.GONE);
            // 4.2 第二个分隔线
            if (isSharing && (isViewed || isBroadcasting)) {
                secondGap.setVisibility(View.VISIBLE);
            } else {
                secondGap.setVisibility(View.GONE);
            }

            // 5.1 主席状态
            tvChair.setVisibility(isCurSiteChair ? View.VISIBLE : View.GONE);
            // 5.2 第一个分隔线
            if (isCurSiteChair && (isSharing || isViewed || isBroadcasting)) {
                firstGap.setVisibility(View.VISIBLE);
            } else {
                firstGap.setVisibility(View.GONE);
            }
        }

        private void notInConfSet() {
            llInConfOpt.setVisibility(View.GONE);
            llNotInConfOpt.setVisibility(View.VISIBLE);
            llInConfStatus.setVisibility(View.GONE);
            llNotInConfStatus.setVisibility(View.VISIBLE);
        }
    }

    class MoreOperationListener implements View.OnClickListener {
        private int position;

        private PopupWindow popupWindow;

        private LinearLayout llBigScrWatch;

        private LinearLayout llHangUp;

        private ConfSiteInfo curSite;

        private boolean isMultiScr;

        /**
         * 构造器
         *
         * @param curSite 当前点击的会场
         */
        public MoreOperationListener(ConfSiteInfo curSite) {
            this.curSite = curSite;
        }

        @Override
        public void onClick(View view) {
            if (view.getTag() instanceof Integer) {
                position = (Integer) view.getTag();
            }
            View moreOperationView = LayoutInflater.from(mContext)
                    .inflate(R.layout.participant_more_operation_layout, null);
            initOperationView(moreOperationView);
            showPopupWindow(view, moreOperationView);
            initEvent();
        }

        /**
         * 在申请主席状态变更时收起弹框
         */
        public void dismissPopWindow() {
            if (popupWindow != null) {
                popupWindow.dismiss();
            }
        }

        private void initEvent() {
            llBigScrWatch.setOnClickListener(view -> handleBigScrWatch());
            llHangUp.setOnClickListener(view -> handleHangUp());
        }

        private void handleHangUp() {
            LogUtil.info(TAG + "handleHangUp() , pos : " + position);
            if (curSite == null || !curSite.isJoinConf()) {
                return;
            }
            if (popupWindow != null) {
                popupWindow.dismiss();
            }
            // 挂端会场 对话框
            showHangUpConfirmDlg();
        }

        private void showHangUpConfirmDlg() {
            CustomFloatWindow.hideFloatWindow(DialogConst.HANG_UP_SITE_DLG);
            CustomFloatWindow hangUpConfirmDlg = new CustomFloatWindow(mContext, DialogConst.HANG_UP_SITE_DLG,
                    mContext.getString(R.string.notice_hangup_site), mContext.getString(R.string.confirm),
                    mContext.getString(R.string.cancel));
            hangUpConfirmDlg.setBthHighLight(FloatWindowCustomBase.HIGH_LIGHT_OK);
            hangUpConfirmDlg.setCallBack(new FloatWindowCustomBase.OnBtnClickCallBack() {
                @Override
                public void isOkBtnClick() {
                    hangUp();
                    CustomFloatWindow.hideFloatWindow(DialogConst.HANG_UP_SITE_DLG);
                }

                @Override
                public void isCancelBtnClick() {
                    CustomFloatWindow.hideFloatWindow(DialogConst.HANG_UP_SITE_DLG);
                }
            });
            hangUpConfirmDlg.showFloatWindow(60);
        }

        private void hangUp() {
            MeetingManager.getInstance()
                    .hangUpAttendee(curSite.getParticipantInfo().getUserId(), new MeetingCallback() {
                        @Override
                        public void onSuccess(Object succMsg) {
                            LogUtil.info(TAG + "hangUp() Success  , succMsg:" + succMsg);
                        }

                        @Override
                        public void onFailed(int errCode, String errMsg) {
                            LogUtil.info(TAG + "hangUp() failed  , errCode : " + errCode + ", errMsg : " + errMsg);
                        }
                    });
        }

        private void handleBigScrWatch() {
            LogUtil.info(TAG + "handleBigScrWatch() , pos : " + position);
            if (popupWindow != null) {
                popupWindow.dismiss();
            }
            if (curSite == null || !curSite.isJoinConf()) {
                return;
            }
            if (curSite.isVoiceSite()) {
                participantsDialog.watchVoiceSiteNotify();
                return;
            }

            // 多画面
            if (isMultiScr) {
                watchMultiScr();
            } else {
                watchSite();
            }
        }

        private void watchSite() {
            MeetingManager.getInstance()
                    .watchAttendee(curSite.getParticipantInfo().getUserId(),
                            new MeetingCallback<ResultMsgInfo>() {
                                @Override
                                public void onSuccess(ResultMsgInfo succMsg) {
                                    LogUtil.info(TAG + "watchSite() success  , succMsg:" + succMsg);
                                }

                                @Override
                                public void onFailed(int errCode, String errMsg) {
                                    LogUtil.info(TAG + "watchSite() failed , errCode : " + errCode + ", errMsg:" + errMsg);
                                    watchErr(errCode);
                                }
                            });
        }

        private void watchMultiScr() {
            MeetingManager.getInstance().watchMultiPic(new MeetingCallback<ResultMsgInfo>() {
                @Override
                public void onSuccess(ResultMsgInfo succMsg) {
                    LogUtil.info(TAG + "watchMultiScr success , " + succMsg);
                }

                @Override
                public void onFailed(int errCode, String errMsg) {
                    LogUtil.info(TAG + "watchMultiScr failed , errCode:" + errCode + ", errMsg:" + errMsg);
                    watchErr(errCode);
                }
            });
        }

        private void watchErr(int errCode) {
            participantsDialog.watchSiteFailedNotify(errCode);
        }

        private void showPopupWindow(View view, View operationView) {
            LogUtil.info(TAG + "showPopupWindow() , pos : " + position);

            // 设置popupWindow 显示位置
            int[] location = new int[2];
            view.getLocationOnScreen(location);
            int viewHeight = view.getHeight();
            int viewWidth = view.getWidth();
            operationView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            int popupHeight = operationView.getMeasuredHeight();
            int popupWidth = operationView.getMeasuredWidth();
            int width = (int) mContext.getResources().getDimension(R.dimen.def_dimens_464);
            popupWindow = new PopupWindow(operationView, width, popupHeight);
            popupWindow.setOutsideTouchable(true);

            // 这里*2才可以输出2160
            int screenHeight = ScreenUtil.getRealWindowHeight(mContext) * 2;
            boolean isNeedUp = (screenHeight - location[1] - viewHeight) < popupHeight + 450;
            int locationX = viewWidth - popupWidth + 48;
            int locationY;
            if (isNeedUp) {
                locationY = location[1] - viewHeight + 24;
            } else {
                locationY = location[1] + viewHeight - 24;
            }
            int yOffUp = -popupHeight - viewHeight + 60;
            showWindow(view, yOffUp, locationX, locationY);
        }

        private void showWindow(View view, int yOffUp, int locationX, int locationY) {
            if (locationY > 1300) {
                popupWindow.showAsDropDown(view, locationX, yOffUp);
            } else {
                popupWindow.showAsDropDown(view, locationX, -12);
            }
        }

        private void initOperationView(View operationView) {
            llBigScrWatch = operationView.findViewById(R.id.ll_watch_big_screen);
            llHangUp = operationView.findViewById(R.id.ll_hang_up);

            if (curSite == null && position >= 0 && position < siteList.size()) {
                GalleryBean galleryBean = siteList.get(position);
                if (galleryBean instanceof ConfSiteInfo) {
                    curSite = (ConfSiteInfo) galleryBean;
                }
            }
            if (curSite == null) {
                return;
            }
            String multiScrStr = mContext.getString(R.string.mutipic_site_txt);
            if (multiScrStr != null && curSite != null && curSite.getParticipantInfo() != null) {
                isMultiScr = (multiScrStr.equals(curSite.getParticipantInfo().getSiteName()));
            }
            if (isMultiScr) {
                llHangUp.setVisibility(View.GONE);
            } else {
                llHangUp.setVisibility(isLocalChair ? View.VISIBLE : View.GONE);
            }
        }
    }
}
